<template>
    <div>
        <div class="container">
            <el-dropdown popper-class="dropDownStyle">
                <span class="el-dropdown-link" ref="titleRef">
                    {{ selectType }}
                    <el-icon class="el-icon--right">
                        <arrow-down />
                    </el-icon>
                </span>
                <template #dropdown>
                    <el-dropdown-menu>
                        <el-dropdown-item @click="changeQueryType($event)">清除查询内容</el-dropdown-item>
                        <el-dropdown-item @click="changeQueryType($event)">事件类型</el-dropdown-item>
                        <el-dropdown-item @click="changeQueryType($event)">发生时间</el-dropdown-item>
                        <el-dropdown-item @click="changeQueryType($event)">发生地点</el-dropdown-item>
                    </el-dropdown-menu>
                </template>
            </el-dropdown>
            <el-input class="w-50 m-2" size="large" placeholder="请输入要查询的内容" :prefix-icon="Search" v-model="searchText"
                @keyup.enter="search">
                <template #append>
                    <span @click="search" style="cursor: pointer;">查询</span>
                </template>
            </el-input>
        </div>

        <div id="search-popup" class="search-popup">
            <a href="#" id="search-popup-closer" class="search-popup-closer"></a>
            <div class="title">
                <span>事件详细信息</span>
            </div>
            <div class="main">
                <table>
                    <tr v-if="isShow">
                        <td>事件编号</td>
                        <td>{{ popupContent.eventNum }}</td>
                    </tr>
                    <tr>
                        <td>事件类型</td>
                        <td>{{ popupContent.eventType }}</td>
                    </tr>
                    <tr>
                        <td>事件等级</td>
                        <td>{{ popupContent.eventClass }}</td>
                    </tr>
                    <tr>
                        <td>发生时间</td>
                        <td>{{ popupContent.time }}</td>
                    </tr>
                    <tr>
                        <td>发生地点</td>
                        <td>{{ popupContent.area }}</td>
                    </tr>
                    <tr  v-if="isShow">
                        <td>车牌号</td>
                        <td>{{ popupContent.carNum }}</td>
                    </tr>
                    <tr  v-if="isShow">
                        <td>驾驶员</td>
                        <td>{{ popupContent.carDriver }}</td>
                    </tr>
                    <tr>
                        <td>处理状态</td>
                        <td>{{ popupContent.eventStatus }}</td>
                    </tr>
                </table>
            </div>
        </div>
    </div>
</template>

<script setup>
import { Search, ArrowDown } from '@element-plus/icons-vue';
import { queryByAttr } from "../../../../utils/QueryByAttrChanged"

const $map = ref(null)
let searchText = ref('')
const searchResult = ref([])
//存放图片标注的图层
const layer = ref(null)

const isShow = ref(true)
if(localStorage.getItem("type")==="common"){
  isShow.value = false
}

onMounted(() => {
    $map.value = inject("$map")
})

const queryType = ref('事件类型')
const selectType = ref('查询类型')

const changeQueryType = (event) => {
    const type = event.target.innerText
    if (type === "清除查询内容") {
        selectType.value = "查询类型"
        searchText.value = ''
        searchResult.value = []
        if (layer.value) {
            $map.value.removeLayer(layer.value)
            $map.value.un("click", handleClick)
        }
        if (popup.value) {
            popup.value.setPosition(undefined);
            closer.value.blur();
        }
        queryType.value = ''
    } else {
        queryType.value = type
        selectType.value = type
    }
}

const search = () => {
    if (searchText.value.trim() === "") {
        ElMessage({
            message: '查询内容不能为空',
            type: 'warning',
        });
        return
    }
    if (layer.value) {
        $map.value.removeLayer(layer.value)
    }
    const field = queryType.value
    const keyword = searchText.value
    const service = {
        name: "guanggu",
        layerId: 2
    }
    queryByAttr({
        field,
        keyword,
        service,
        callback: handleQuery
    })
}
const popupContent = ref([])
let closer = ref(null)
let popup = ref(null)
const handleQuery = (data) => {
    if (data.SFEleArray.length === 0) {
        ElMessage({
            message: '查询结果为空',
            type: 'warning',
        });
        $map.value.removeLayer(layer.value)
        return
    }
    //数据处理 获取信息
    searchResult.value = data.SFEleArray.map(item => {
        //事件等级数组
        const eventClassArr = ["轻微事故", "一般事故", "重大事故", "特大事故"]
        //事件处理状态数组
        const eventStatusArr = ["待处理", "处理中", "已归档"]
        //事件坐标
        const position = [item.fGeom.PntGeom[0].Dot.x, item.fGeom.PntGeom[0].Dot.y]
        return {
            eventNum: item.AttValue[0],
            eventType: item.AttValue[1],
            eventClass: eventClassArr[+item.AttValue[2] - 1],
            time: item.AttValue[3],
            area: item.AttValue[4],
            carNum: item.AttValue[5],
            carDriver: item.AttValue[6],
            eventStatus: eventStatusArr[+item.AttValue[7]],
            position
        }
    })

    //生成geojson数据
    const geojson = {
        type: "FeatureCollection",
        features: []
    }
    searchResult.value.forEach(item => {
        geojson.features.push({
            type: "Feature",
            geometry: {
                type: "Point",
                coordinates: item.position,
                properties: {
                    name: item.eventClass
                }
            }
        })
    })
    const source = new ol.source.Vector({
        features: new ol.format.GeoJSON().readFeatures(geojson)
    })
    layer.value = new ol.layer.Vector({
        source,
        style: new ol.style.Style({
            /**{olx.style.IconOptions}类型*/
            image: new ol.style.Icon({
                anchor: [0.5, 60],
                anchorOrigin: 'top-right',
                anchorXUnits: 'fraction',
                anchorYUnits: 'pixels',
                offsetOrigin: 'top-right',
                scale: 0.5,
                //透明度
                opacity: 1,
                //图标的url
                src: 'src/img/dingwei.png',
            }),
        })
    })
    $map.value.addLayer(layer.value)

    $map.value.on("click", handleClick)
}

const handleClick = (e) => {
    const feature = $map.value.forEachFeatureAtPixel(
        e.pixel,
        function (feature, layer) {
            return feature
        }
    )
    if (feature) {
        const coordinate = feature.getGeometry().flatCoordinates
        //获取点击标注对应的属性
        searchResult.value.forEach(item => {
            if (item.position[0] === coordinate[0] & item.position[1] === coordinate[1]) {
                popupContent.value = item
            }
        })

        let container = document.getElementById('search-popup');
        closer.value = document.getElementById('search-popup-closer');
        popup.value = new ol.Overlay({
            //要转换成overlay的HTML元素
            element: container,
            //当前窗口可见
            autoPan: true,
            //Popup放置的位置
            positioning: 'bottom-center',
            //是否应该停止事件传播到地图窗口
            stopEvent: true,
            autoPanAnimation: {
                //当Popup超出地图边界时，为了Popup全部可见，地图移动的速度
                duration: 250,
            },
        });
        $map.value.addOverlay(popup.value);

        //添加关闭按钮的单击事件（隐藏popup）
        closer.value.onclick = function () {
            //未定义popup位置
            popup.value.setPosition(undefined);
            //失去焦点
            closer.value.blur();
            return false;
        };
        popup.value.setPosition(coordinate)
        container.style.display = 'block';
    }
}

</script>

<style lang="scss" scoped>
.container {
    display: flex;

    .el-dropdown {
        width: 120px;
        display: flex;
        align-items: center;
        font-size: 15px;
        color: #303030;
        cursor: pointer;

        :deep(:focus-visible) {
            outline: none !important;
        }

        :global(.dropDownStyle .el-dropdown-menu__item) {
            display: flex;
            justify-content: center;
        }

        .el-input {
            width: 260px;
        }
    }
}

.search-popup {
    position: absolute;
    width: 340px;
    background-color: white;
    padding-bottom: 18px;
    -webkit-filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2));
    filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2));
    border: 1px solid #cccccc;
    border-radius: 5px;
    bottom: 45px;
    display: none;
    left: -50px;
    z-index: 999;

    &:after,
    &:before {
        top: 100%;
        border: solid transparent;
        content: ' ';
        height: 0;
        width: 0;
        position: absolute;
        pointer-events: none;
    }

    &:after {
        border-top-color: white;
        border-width: 10px;
        left: 48px;
        margin-left: -10px;
    }

    &:before {
        border-top-color: #cccccc;
        border-width: 11px;
        left: 48px;
        margin-left: -11px;
    }

    .search-popup-closer {
        text-decoration: none;
        position: absolute;
        top: 2px;
        right: 8px;
    }

    .search-popup-closer:after {
        content: '✖';
    }

    .title {
        background-color: #2196f3;
        padding: 4px 5px;
        font-size: 15px;
        color: #fff;
        border-radius: 5px 5px 0 0;
    }
}

.main {
    padding: 10px;
    font-size: 15px;

    table {
        display: flex;
        flex-direction: column;
        width: 100%;

        tr {
            display: flex;

            td {
                padding: 7px 15px;
                border: 1px solid #ededed;

                &:first-child {
                    color: #656565;
                    font-weight: 600;
                    width: 40%;
                }

                &:last-child {
                    width: 60%;
                }
            }
        }
    }
}
</style>